//
//  NIBaseViewModel.m
//  AIWAYS
//
//  Created by Marx on 2018/7/17.
//  Copyright © 2018年 wlq. All rights reserved.
//

#import "NIBaseViewModel.h"
#import "AFURLSessionManager.h"
#import "NotificationDefines.h"

@implementation NIBaseViewModel




- (void)downloadinNewImage:(NSString *)url userId:(NSString *)userId{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载头像进度 = %@",downloadProgress);
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        NSFileManager *manager = [NSFileManager defaultManager];
        NSString *path = [self getAvatarImagePathWithUserID:userId url:url];
        NSURL *fileUrl = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",path]];
        
        if ([manager isDeletableFileAtPath:[fileUrl path]]) {
            NSError *error;
            [manager removeItemAtPath:[fileUrl path] error:&error];
            if(error){
                return fileUrl;
            }
        }
        return fileUrl;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (!error) {
            //通知，头像下载完毕，对应界面刷新
            NSLog(@"通知，头像下载完毕，对应界面刷新");
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationAvatarLoadFinish object:nil];
        }
        
    }];
    [downloadTask resume];
}


/**
 获取账号对应的头像图片，在本地沙盘储存的路径
 
 @param userId 用户id
 @return 路径
 */
-(NSString *)getAvatarImagePathWithUserID:(NSString *)userId url:(NSString *)url
{
    NSString *idStr = @"";
    NSArray *array = [url componentsSeparatedByString:@"/"];
    if (array.count > 0) {
        NSString *str = [array lastObject];
        NSArray *tempArray = [str componentsSeparatedByString:@"."];
        if (tempArray.count > 0) {
            idStr = tempArray[0];
        }
    }
    NSString *fileName = [NSString stringWithFormat:@"avatar__%@__%@.jpg",userId,idStr];
    NSString *path = [[self getAvatarImageFolderPath] stringByAppendingPathComponent:fileName];
    return path;
}



-(NSString *) getAvatarImageFolderPath
{
    NSString * documentsPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
    // 在Documents文件夹中创建文件夹
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *PDFDirectory = [documentsPath stringByAppendingPathComponent:@"HavalAvatarImage"];
    if (![fileManager fileExistsAtPath:PDFDirectory]) {
        [fileManager createDirectoryAtPath:PDFDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return PDFDirectory;
}

-(UIImage *)getAvatarImageWithUrl:(NSString *)url userId:(NSString *)userId
{
    UIImage *avatarImage;
    NSString *imagePath = [self getAvatarImagePathWithUserID:userId url:url];
    if([[NSFileManager defaultManager] fileExistsAtPath:imagePath]){
        avatarImage = [UIImage imageWithContentsOfFile:imagePath];
        if (avatarImage == nil) {
            [self downloadinNewImage:url userId:userId];
        }
    }
    else
    {
        [self downloadinNewImage:url userId:userId];
    }
    return avatarImage;
}
@end
